package cse3311.calendarapp.gui;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.GregorianCalendar;
import java.util.List;

import android.annotation.TargetApi;
import android.app.ActionBar;
import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.os.Build;
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.GridView;

import com.parse.Parse;

import cse3311.calendarapp.R;
import cse3311.calendarapp.StorageManager;

public class MainActivity extends FragmentActivity implements
		ActionBar.OnNavigationListener, OnClickListener {
	private GridCellAdapter adapter;
	private GridView calendarView;
	private int month_m;
	private int year_m;

	/**
	 * The serialization (saved instance state) Bundle key representing the
	 * current dropdown position.
	 */
	private static final String STATE_SELECTED_NAVIGATION_ITEM = "selected_navigation_item";

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.month_view);
		// Set up the action bar to show a dropdown list.
		final ActionBar actionBar = getActionBar();
		actionBar.setDisplayShowTitleEnabled(false);
		actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_LIST);

		calendarView = (GridView) this.findViewById(R.id.monthView);

		GregorianCalendar now = new GregorianCalendar();
		month_m = now.get(GregorianCalendar.MONTH);
		year_m = now.get(GregorianCalendar.YEAR);
		Log.d("main", "month: " + month_m);

		updateMonthView(month_m, year_m);

		// Set up the dropdown list navigation in the action bar.
		actionBar.setListNavigationCallbacks(
		// Specify a SpinnerAdapter to populate the dropdown list.
				new ArrayAdapter<String>(getActionBarThemedContextCompat(),
						android.R.layout.simple_list_item_1,
						android.R.id.text1, new String[] { "January",
								"February", "March", "April", "May", "June",
								"July", "August", "September", "October",
								"November", "December" }), this);
		actionBar.setSelectedNavigationItem(month_m);

//		Parse.initialize(this, "6soa7TNl1GuaZ5JomFxdSMJxmaEQQ8mCzFtSEpva",
//				"eaFq5CPew3EBBM0VP77eALg8OwJtMVid6UaEygVE");
		StorageManager.loadCalendar(getApplicationContext().getFilesDir());
	}

	@Override
	protected void onDestroy() {
		super.onDestroy();
		StorageManager.saveCalendar(getApplicationContext().getFilesDir());
	}

	/**
	 * Backward-compatible version of {@link ActionBar#getThemedContext()} that
	 * simply returns the {@link android.app.Activity} if
	 * <code>getThemedContext</code> is unavailable.
	 */
	@TargetApi(Build.VERSION_CODES.ICE_CREAM_SANDWICH)
	private Context getActionBarThemedContextCompat() {
		if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.ICE_CREAM_SANDWICH) {
			return getActionBar().getThemedContext();
		} else {
			return this;
		}
	}

	@Override
	public void onRestoreInstanceState(Bundle savedInstanceState) {
		// Restore the previously serialized current dropdown position.
		if (savedInstanceState.containsKey(STATE_SELECTED_NAVIGATION_ITEM)) {
			getActionBar().setSelectedNavigationItem(
					savedInstanceState.getInt(STATE_SELECTED_NAVIGATION_ITEM));
		}
	}

	@Override
	public void onSaveInstanceState(Bundle outState) {
		// Serialize the current dropdown position.
		outState.putInt(STATE_SELECTED_NAVIGATION_ITEM, getActionBar()
				.getSelectedNavigationIndex());
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.main, menu);
		return true;
	}

	@Override
	public boolean onNavigationItemSelected(int position, long id) {
		// When the given dropdown item is selected, show its contents in the
		// container view.
		updateMonthView(position, year_m);
		return true;
	}

	public void updateMonthView(int month, int year) {
		month_m = month;
		year_m = year;
		adapter = new GridCellAdapter(month, year);
		adapter.notifyDataSetChanged();
		calendarView.setAdapter(adapter);
	}

	@Override
	public void onClick(View view) {
		GregorianCalendar calendar = (GregorianCalendar) view.getTag();
		Intent dayViewIntent = new Intent(this, DayViewActivity.class);
		dayViewIntent.putExtra("date", calendar);
		startActivity(dayViewIntent);
	}

	private class GridCellAdapter extends BaseAdapter {
		private static final String tag = "GridCellAdapter";

		private List<DayButton> list;
		private Button gridcell;

		public class DayButton {
			public int color;
			public GregorianCalendar calendar;
		}

		// Days in Current Month
		public GridCellAdapter(int month, int year) {
			super();
			generateMonth(month, year);
		}

		@Override
		public DayButton getItem(int position) {
			return list.get(position);
		}

		@Override
		public int getCount() {
			return list.size();
		}

		private void generateMonth(int month, int year) {
			list = new ArrayList<DayButton>();

			GregorianCalendar thisMonthCalendar = new GregorianCalendar(year,
					month, 1);
			int daysInMonth = thisMonthCalendar
					.getActualMaximum(GregorianCalendar.DAY_OF_MONTH);

			int prevMonth = 0;
			int prevYear = 0;
			int nextMonth = 0;
			int nextYear = 0;

			if (month == 11) {
				prevMonth = 10;
				nextMonth = 0;
				prevYear = year;
				nextYear = year + 1;
			} else if (month == 0) {
				prevMonth = 11;
				prevYear = year - 1;
				nextYear = year;
				nextMonth = 1;
			} else {
				prevMonth = month - 1;
				nextMonth = month + 1;
				nextYear = year;
				prevYear = year;
			}

			GregorianCalendar prevMonthCalendar = new GregorianCalendar(
					prevYear, prevMonth, 1);
			int daysInPrevMonth = prevMonthCalendar
					.getActualMaximum(GregorianCalendar.DAY_OF_MONTH);

			// Compute how much to leave before before the first day of the
			// month.
			// getDay() returns 0 for Sunday.
			int trailingSpaces = thisMonthCalendar.get(Calendar.DAY_OF_WEEK) - 1;

			// Trailing Month days
			for (int i = 0; i < trailingSpaces; i++) {
				DayButton button = new DayButton();
				button.color = Color.WHITE;
				int day = daysInPrevMonth - trailingSpaces + i + 1;
				button.calendar = new GregorianCalendar(prevYear, prevMonth,
						day);
				list.add(button);
			}

			// Current Month Days
			for (int i = 1; i <= daysInMonth; i++) {
				DayButton button = new DayButton();
				button.color = Color.GRAY;
				button.calendar = new GregorianCalendar(year, month, i);
				list.add(button);
			}

			// Leading Month days
			int leadingDays = 7 - list.size() % 7;
			if (leadingDays == 7)
				leadingDays = 0;
			for (int i = 0; i < leadingDays; i++) {
				DayButton button = new DayButton();
				button.color = Color.WHITE;
				button.calendar = new GregorianCalendar(nextYear, nextMonth,
						i + 1);
				list.add(button);
			}
		}

		@Override
		public long getItemId(int position) {
			return position;
		}

		@Override
		public View getView(int position, View convertView, ViewGroup parent) {
			Log.d(tag, "getView ...");
			View row = convertView;
			if (row == null) {
				// ROW INFLATION
				Log.d(tag, "Starting XML Row Inflation ... ");
				LayoutInflater inflater = (LayoutInflater) MainActivity.this
						.getApplicationContext().getSystemService(
								Context.LAYOUT_INFLATER_SERVICE);
				row = inflater.inflate(R.layout.gridcell, parent, false);

				Log.d(tag, "Successfully completed XML Row Inflation!");
			}

			gridcell = (Button) row.findViewById(R.id.gridcell);
			gridcell.setOnClickListener(MainActivity.this);

			// ACCOUNT FOR SPACING
			DayButton button = list.get(position);

			gridcell.setText(""
					+ button.calendar.get(GregorianCalendar.DAY_OF_MONTH));
			gridcell.setTag(button.calendar);
			gridcell.setTextColor(button.color);

			return row;
		}
	}
}